package swa.telco.impl;

import java.util.Collection;

import swa.telco.interfaces.ClientProviderInt;
import swa2012.telco.broker.beans.BrokerSendMessageStatus;
import swa2012.telco.broker.beans.Client;
import swa2012.telco.broker.beans.Message;

public class ImplClientProvider implements ClientProviderInt {

	private SWAProvider provider;
	private OnlineClients onlineClients;
	private MessageContainer msgContainer;
	
	public ImplClientProvider(SWAProvider provider, OnlineClients onlineClients, MessageContainer msContainer){
		this.provider = provider;
		this.onlineClients = onlineClients;
		this.msgContainer = msContainer;
	}
	
	@Override
	public Client register(String clientID) {
		Client tmpClient = new Client(clientID, provider.getBeanOfProvider());
		onlineClients.add(tmpClient);
		return tmpClient;
	}

	@Override
	public boolean deregister(String clientID) {
		try{
			onlineClients.remove(clientID);
		}catch (Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean sendMessage(Message msg) {
		msg.setTimestamp(Long.valueOf(System.currentTimeMillis()));
		
		if(msg.getReceiver()!=null && msg.getSender()!= null && !msg.getText().isEmpty()){
			if(msg.getReceiver().getProvider().getID().equals(provider.getBeanOfProvider().getID())){
				msgContainer.add(msg);
			}
			else{
				BrokerSendMessageStatus stat = provider.getBroker().sendMessage(msg);
				if(!stat.equals(BrokerSendMessageStatus.SEND_MESSAGE_ERROR))
					return true;
				else return false;
			}
		}
		return false;
	}

	@Override
	public Collection<Message> getMessages(String clientID) {
		return msgContainer.getMessages(clientID);
	}

	@Override
	public Collection<Client> listAllClients() {
		return provider.getBroker().listClients();
	}

}
